﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

using Microsoft.VisualBasic.PowerPacks.Printing;

namespace auxiliary_proj
{
    public partial class FormOrderSummary : Form
    {
        MySqlConnection connection;
        DataTable table;

        int order_id;
        string unitName = "";
        string status;
        string approvedBy = "";
        string balance = "";

        public FormOrderSummary() { }

        public FormOrderSummary(int order_id, string unitName, string status, string date, string approvedBy, string balance)
        {
            InitializeComponent();
            connection = new MySqlConnection(Program.getConnection());
            this.OrderNumLable.Text = "" + order_id;
            this.OrderUnitNameLabel.Text = "" + unitName;
            this.OrderStatusLabel.Text = "" + status;
            this.OrderDateLabel.Text = "" + date;
            this.order_id = order_id;
            this.unitName = unitName;
            this.status = status;
            this.approvedBy = approvedBy;
            this.balance = balance;
            lbApprovedBy.Text = approvedBy;
            cbApprovalMsg.Text = "I, " + Employee.Name + ", hereby approve this " + status.ToLower() + " order";
            cbApprovalMsg.Location = new Point(cbApprovalMsg.Location.X - cbApprovalMsg.Width + 15, cbApprovalMsg.Location.Y);
            query();

        }
        //Query that selects the order items for the specific order
        public void query()
        {
            string query = "Select i.item_id, i.description, i.actual_price, io.quantity FROM S_ORDER AS s, ITEM AS i, ITEM_ORDER AS io WHERE s.order_id = io.order_id AND io.item_id = i.item_id AND s.order_id='" + order_id + "'";
            try
            {
                connection.Open();
                try
                {
                    table = new DataTable();
                    table = Query.select(query);
                    OrderSummaryDataGrid.DataSource = table;
                }
                catch (MySqlException exc) { MessageBox.Show(exc.Message); }
            }
            catch (DataException ex) { MessageBox.Show(ex.Message); }
            finally
            {
                connection.Close();
            }
        }
        //updates the quantity afte a reader as been processed
        public void quantityUpdate()
        {
            for(int i = 0; i<table.Rows.Count; i++)
            {
                int askingQuantity = int.Parse(table.Rows[i]["quantity"].ToString());

                DataTable result = Query.select("SELECT item_id, quantity, timestamp FROM item_quantity WHERE item_id = '"+ table.Rows[i]["item_id"].ToString() + "' ORDER BY timestamp");
                
                foreach(DataRow row in result.Rows)
                {
                    int rowQuantity = int.Parse(row["quantity"].ToString());

                    if (rowQuantity - askingQuantity <= 0)
                    {
                        askingQuantity -= rowQuantity;
                        //remove row
                        string q = "DELETE FROM item_quantity WHERE item_id = '" + int.Parse(row["item_id"].ToString()) + "' AND timestamp = '" + ((DateTime)row["timestamp"]).ToString("yyyy-MM-dd HH:mm:ss") +"'";
                        //MessageBox.Show(q);
                        Query.nonQuery(q);
                    }
                    else
                    {
                        //update row quantity with current quantity in row - asking quantity
                        string q2 = "UPDATE item_quantity SET quantity = '" + (int.Parse(row["quantity"].ToString()) - askingQuantity) + "' WHERE item_id = '" + int.Parse(row["item_id"].ToString()) + "' AND timestamp = '" + ((DateTime)row["timestamp"]).ToString("yyyy-MM-dd HH:mm:ss") + "'";
                        Query.nonQuery(q2);
                        break;
                    }

                    if (askingQuantity == 0)
                        break;
                }
            }
        }

        //calculate the total price for the order
        public double totalPrice()
        {
            double totalPrice = 0;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                totalPrice += (double)table.Rows[i]["actual_price"] * (int)table.Rows[i]["quantity"];
            }
            return totalPrice;
        }
        //changes the status from string to a number
        private int statusNumber(string name)
        {
            int num = 0;
            switch (name.ToLower())
            {
                case "pending":
                    num = 0;
                    break;
                case "active":
                    num = 1;
                    break;
                case "ready to ship":
                    num = 2;
                    break;
                case "shipped":
                    num = 3;
                    break;
            }
            return num;
        }

        //approves the order
        private void btnApprove_Click(object sender, EventArgs e)
        {
            if (cbApprovalMsg.Checked)
            {
                string query = "update S_ORDER set status=" + (statusNumber(this.status) + 1) + " where order_id='" + order_id + "'";
                string queryApprovedBy = "update S_ORDER set ApprovedBy = '" + Employee.Name + "' where order_id='" + order_id + "'";
                if (statusNumber(this.status) == 2)
                {
                    tbOrderTotal.Text = UCUnits.balanceFormat((double)totalPrice());
                    double accountBalance = double.Parse(balance) - (double)totalPrice();

                    if (accountBalance < 0)
                    {
                        MessageBox.Show("Insufficient funds for " + unitName + "!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    else if (MessageBox.Show("The total amount for this order is " + UCUnits.balanceFormat((double)totalPrice()) + ", which will be deducted from " + unitName + "'s account. Their total account balance is " + UCUnits.balanceFormat(double.Parse(balance)) + ".\nThe Account Balance will be " + UCUnits.balanceFormat(accountBalance) + ". Do you want to continue?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        string update = "UPDATE UNIT set Balance = '" + accountBalance + "' where name='" + unitName + "'";
                        Query.nonQuery(update);
                        quantityUpdate();
                        Query.nonQuery(query);
                        Query.nonQuery(queryApprovedBy);
                        Singleton.getUCOrderStatus().qSalesOrder();
                        this.Dispose();
                    }
                }
                if (statusNumber(this.status) != 2)
                {
                    Query.nonQuery(query);
                    Query.nonQuery(queryApprovedBy);
                    Singleton.getUCOrderStatus().qSalesOrder();
                    this.Dispose();
                } 
            }
            else
                MessageBox.Show("You must Agree to the terms to continue!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            if (Employee.Permission == 2)
            {
                Singleton.getMainForm().qNewPendingSalesOrderCount();
            }
            else if (Employee.Permission == 1)
                Singleton.getMainForm().qNewActiveSalesOrderCount();
            else
                /* user shouldnt see this, ALT+F4! */
                Singleton.getMainForm().Close();
        }
    }
}
